package org.shiro.demo.service.impl;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.joda.time.DateTime;
import org.shiro.demo.entity.MPWeixinToken;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IMPWeixinTokenService;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.utils.CommonUtil;

@Service("weixinTokenService")
public class MPWeixinTokenServiceImpl extends DefultBaseService implements IMPWeixinTokenService {
	@Resource(name = "baseService")
	private IBaseService baseService;

	// 使用了一个缓存名叫 weixintoken
	@Cacheable("weixintoken")
	public MPWeixinToken get(int id) {
		MPWeixinToken token = baseService.getById(MPWeixinToken.class, id);// 只有一条
		if (token == null) {
			JSONObject jsonObject = CommonUtil.httpsRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1d8e9a967a8c62bd&secret=c687ad8537af8d8e1ca2fc573095a426", "GET", null);
			token = new MPWeixinToken();
			token.setId(1);
			token.setAccess_token((String) jsonObject.get("access_token"));
			token.setExpires_in(7200);
			DateTime now = new DateTime();
			token.setExpires_time(now.plusSeconds(7100).toDate());
			baseService.save(token);
		}
		return token;
	}

	@Override
	@CachePut(value = "weixintoken", key = "#id")
	// 缓存key忽略mid
	public MPWeixinToken update(int id) {
		MPWeixinToken token = new MPWeixinToken();
		try {
			// 重新获取token
			JSONObject jsonObject = CommonUtil.httpsRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1d8e9a967a8c62bd&secret=c687ad8537af8d8e1ca2fc573095a426", "GET", null);
			token.setId(1);
			token.setAccess_token((String) jsonObject.get("access_token"));
			token.setExpires_in(7200);
			DateTime now = new DateTime();
			token.setExpires_time(now.plusSeconds(7100).toDate());

			// 更新 状态
			baseService.update(token);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return token;
	}

}
